package com.wans.gateway.exception;

import com.wans.common.exception.CustomRunningException;
import com.wans.common.result.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
@Slf4j
@SuppressWarnings({"all"})
public class GlobalExceptionHandler {

    // 处理自定义异常 - 运行已知异常
    @ExceptionHandler(CustomRunningException.class)
    public ResponseEntity<ResponseResult<Void>> handleUserRegisterException(CustomRunningException customRunningException) {

        log.error(customRunningException.getErrorCode().toString(), customRunningException.getErrorMessage());

        customRunningException.printStackTrace();

        return ResponseEntity
                .status(HttpStatus.UNPROCESSABLE_ENTITY)
                .body(ResponseResult.fail(
                        customRunningException.getErrorCode(),
                        customRunningException.getErrorMessage()
                )); // 返回字段级错误
    }


    /**
     * 其他未知的异常
     *
     * @param ex 未知异常信息
     * @return 错误信息
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseResult<Void>> handleOtherExceptions(Exception exception) {
        log.error(exception.getMessage());
        exception.printStackTrace();
        return new ResponseEntity<>(ResponseResult.fail(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}